import {
  BAIDUMAP_AK,
  QQMAP_AK
} from '@/config'

/**
 * 深拷贝
 * @param {*} source 拷贝对象
 */
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'shallowClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(key => {
    if (source[key] && typeof source[key] === 'object') {
      targetObj[key] = deepClone(source[key])
    } else {
      targetObj[key] = source[key]
    }
  })
  return targetObj
}

export function debounce(func, delay = 100, immediate = true) {
  let timer, context, args

  const laterFunc = function () {
    setTimeout(() => {
      timer = null
      if (!immediate) {
        func.apply(context, args)
        context = args = null
      }
    }, delay)
  }

  return function (...params) {
    if (!timer) {
      timer = laterFunc()
      if (immediate) {
        func.apply(this, params)
      } else {
        context = this
        args = params
      }
    } else {
      clearTimeout(timer)
      timer = laterFunc()
    }
  }
}

export function loadMapScript(type) {
  return new Promise((resolve, reject) => {
    let mapGlobal,
      scriptSrc

    window.loadMapCompleted = () => {
      resolve()
    }

    if (type === 'baidu') {
      mapGlobal = window.BMap
      scriptSrc = `http://api.map.baidu.com/api?v=2.0&ak=${BAIDUMAP_AK}&callback=loadMapCompleted`
    } else {
      mapGlobal = window.qq
      scriptSrc = `https://map.qq.com/api/js?v=2.exp&key=${QQMAP_AK}&callback=loadMapCompleted`
    }

    if (mapGlobal !== undefined) {
      return resolve()
    }
    const script = document.createElement('script')
    script.src = scriptSrc
    script.error = reject

    document.body.appendChild(script)
  })
}

export function formValidate(elForm) {
  return new Promise((resolve, reject) => {
    elForm.validate(valid => {
      resolve(valid)
    })
  })
}

export function thousandSplit(num) {
  if (!num || isNaN(num)) {
    return 0
  }

  const reg = new RegExp(/(\d)(?=(?:\d{3})+$)/g)

  const numStr = num.toString()
  // 判断是否是float
  if (numStr.indexOf('.') > -1) {
    const numArr = (num - 0).toFixed(2).split('.')
    return numArr[0].replace(reg, '$1,') + '.' + numArr[1]
  } else {
    return numStr.replace(reg, '$1,')
  }
}

export function clickCopy(text) {
  let input = document.createElement('input')
  input.value = text
  document.body.appendChild(input)
  input.select()
  document.execCommand('Copy')
  document.body.removeChild(input)
  input = null
  this.$message.success(this.$t('utils.copySuccess'))
}

export function dynamicLoadScript(url) {
  return new Promise((resolve, reject) => {
    const nodeList = document.querySelectorAll(`script[src="${url}"]`)
    if (nodeList.length) {
      resolve()
      return
    }
    const script = document.createElement('script')
    script.src = url
    document.body.appendChild(script)

    script.onload = () => {
      resolve()
    }
    script.onerror = err => {
      reject(err)
    }
  })
}
